#include "infrared.h"
#include <mcs51/8052.h>
#include "timer0.h"

unsigned char Read_Ir_value[5]; // 存储4个字节接收码（地址码+地址反码+控制码+控制反码）
unsigned int wait_time;

int state = 0;
unsigned char bit_index = 0;

void infrared_init(void)
{
    IT0 = 1; // 下降沿触发
    IE0 = 0;
    EX0 = 1; // 打开中断0允许
    EA = 1;  // 打开总中断
    PX0 = 1;
    IRIN = 1; // 初始化端口
    Timer0_init();
}

void infrared_routine(void) __interrupt(0) // 外部中断0服务函数
{
    if (state == 0)
    {
        Timer0_start();
        state = 1;
    }
    else if (state == 1)
    {
        unsigned int time = Timer0_restart();
        if (time > 4500 - 500 && time < 4500 + 500)
        {
            state = 2;
            bit_index = 0;
            Read_Ir_value[0] = 0x00;
            Read_Ir_value[1] = 0x00;
            Read_Ir_value[2] = 0x00;
            Read_Ir_value[3] = 0x00;
            Read_Ir_value[4] = 0x00;
        }
        else
        {
            state = 1;
            Read_Ir_value[4] = 0xE1;
        }
    }
    else if (state == 2)
    {
        unsigned int time = Timer0_restart();
        wait_time = time;
        int byte_index = bit_index / 8;
        if (time > 1250 - 300 && time < 1250 + 300)
        {
            Read_Ir_value[byte_index] = Read_Ir_value[byte_index] >> 1;
            bit_index++;
        }
        else if (time > 2250 - 300 && time < 2250 + 300)
        {
            Read_Ir_value[byte_index] = Read_Ir_value[byte_index] | 0x80;
            Read_Ir_value[byte_index] = Read_Ir_value[byte_index] >> 1;
            bit_index++;
        }
        else
        {
            Read_Ir_value[4] = 0xE2;
            Read_Ir_value[0] = bit_index;
            wait_time = time;
            state = 4;
        }
        if (bit_index == 32)
        {
            state = 3;
            Read_Ir_value[4] = 0xAA;
        }
    }
    else if (state == 3)
    {
        Read_Ir_value[4] = 0xE3;
    }
}